"""EDA指标计算算法实现

提供多种EDA分析指标的计算功能：
- 基础指标计算：基本统计量和SCR相关指标
- 高级指标计算：频域分析、复杂度指标等
- 批量指标计算：一次性计算所有指标

所有计算函数返回指标字典，键为指标名称，值为计算结果。
"""

import numpy as np
from scipy import signal, stats
from scipy.fft import fft, fftfreq
from typing import Dict, Any, Optional, Tuple
import logging

logger = logging.getLogger(__name__)

def calculate_metrics_basic(eda_signal: np.ndarray, peaks: np.ndarray, 
                          peak_properties: Dict[str, Any], 
                          sampling_rate: float = 4.0) -> Dict[str, float]:
    """计算基础EDA指标
    
    包括基本统计量和SCR相关的基础指标。
    
    Args:
        eda_signal: EDA信号数据
        peaks: 峰值位置数组
        peak_properties: 峰值属性字典
        sampling_rate: 采样率（Hz）
        
    Returns:
        指标字典
    """
    try:
        logger.debug("开始计算基础EDA指标")
        metrics = {}
        
        # 处理NaN值
        valid_mask = ~np.isnan(eda_signal)
        valid_signal = eda_signal[valid_mask]
        
        if len(valid_signal) == 0:
            logger.warning("没有有效的EDA数据")
            return _get_empty_metrics()
        
        # 1. 基本统计指标
        metrics['mean_eda'] = float(np.mean(valid_signal))
        metrics['std_eda'] = float(np.std(valid_signal))
        metrics['min_eda'] = float(np.min(valid_signal))
        metrics['max_eda'] = float(np.max(valid_signal))
        metrics['range_eda'] = metrics['max_eda'] - metrics['min_eda']
        
        # 2. SCR相关指标
        num_peaks = len(peaks)
        signal_duration = len(eda_signal) / sampling_rate  # 信号总时长（秒）
        
        metrics['scr_count'] = float(num_peaks)
        metrics['scr_rate'] = float(num_peaks / signal_duration * 60) if signal_duration > 0 else 0.0  # 每分钟SCR数
        
        if num_peaks > 0 and 'peak_heights' in peak_properties:
            peak_heights = peak_properties['peak_heights']
            
            # SCR幅度相关
            metrics['scr_amplitude_mean'] = float(np.mean(peak_heights))
            metrics['scr_amplitude_std'] = float(np.std(peak_heights))
            metrics['scr_amplitude_max'] = float(np.max(peak_heights))
            metrics['scr_amplitude_sum'] = float(np.sum(peak_heights))
            
            # SCR宽度相关（如果有宽度信息）
            if 'widths' in peak_properties and len(peak_properties['widths']) > 0:
                widths = peak_properties['widths']
                metrics['scr_width_mean'] = float(np.mean(widths))
                metrics['scr_width_std'] = float(np.std(widths))
            else:
                metrics['scr_width_mean'] = 0.0
                metrics['scr_width_std'] = 0.0
            
            # SCR间隔相关
            if num_peaks > 1:
                intervals = np.diff(peaks) / sampling_rate  # 转换为秒
                metrics['scr_interval_mean'] = float(np.mean(intervals))
                metrics['scr_interval_std'] = float(np.std(intervals))
            else:
                metrics['scr_interval_mean'] = 0.0
                metrics['scr_interval_std'] = 0.0
        else:
            # 没有峰值时的默认值
            metrics.update({
                'scr_amplitude_mean': 0.0,
                'scr_amplitude_std': 0.0,
                'scr_amplitude_max': 0.0,
                'scr_amplitude_sum': 0.0,
                'scr_width_mean': 0.0,
                'scr_width_std': 0.0,
                'scr_interval_mean': 0.0,
                'scr_interval_std': 0.0
            })
        
        # 3. SCL（皮肤电导水平）相关指标
        # 使用低通滤波提取SCL成分
        try:
            # 设计低通滤波器（截止频率0.05Hz）
            nyquist = sampling_rate / 2
            low_cutoff = 0.05 / nyquist
            b, a = signal.butter(2, low_cutoff, btype='low')
            scl_signal = signal.filtfilt(b, a, eda_signal)
            
            # 去除NaN
            valid_scl = scl_signal[valid_mask]
            
            metrics['scl_mean'] = float(np.mean(valid_scl))
            metrics['scl_std'] = float(np.std(valid_scl))
            metrics['scl_slope'] = float(_calculate_trend_slope(valid_scl))
            
        except Exception as e:
            logger.warning(f"SCL计算失败: {str(e)}")
            metrics.update({
                'scl_mean': metrics['mean_eda'],
                'scl_std': 0.0,
                'scl_slope': 0.0
            })
        
        logger.debug(f"基础指标计算完成，共计算 {len(metrics)} 个指标")
        return metrics
        
    except Exception as e:
        logger.error(f"基础指标计算失败: {str(e)}")
        return _get_empty_metrics()

def calculate_metrics_advanced(eda_signal: np.ndarray, peaks: np.ndarray, 
                             peak_properties: Dict[str, Any], 
                             sampling_rate: float = 4.0) -> Dict[str, float]:
    """计算高级EDA指标
    
    包括频域分析、复杂度指标、非线性特征等。
    
    Args:
        eda_signal: EDA信号数据
        peaks: 峰值位置数组
        peak_properties: 峰值属性字典
        sampling_rate: 采样率（Hz）
        
    Returns:
        指标字典
    """
    try:
        logger.debug("开始计算高级EDA指标")
        metrics = {}
        
        # 处理NaN值
        valid_mask = ~np.isnan(eda_signal)
        valid_signal = eda_signal[valid_mask]
        
        if len(valid_signal) < 10:
            logger.warning("有效数据点太少，无法计算高级指标")
            return _get_empty_advanced_metrics()
        
        # 1. 频域分析
        try:
            freq_metrics = _calculate_frequency_metrics(valid_signal, sampling_rate)
            metrics.update(freq_metrics)
        except Exception as e:
            logger.warning(f"频域分析失败: {str(e)}")
            metrics.update(_get_empty_frequency_metrics())
        
        # 2. 信号复杂度指标
        try:
            complexity_metrics = _calculate_complexity_metrics(valid_signal)
            metrics.update(complexity_metrics)
        except Exception as e:
            logger.warning(f"复杂度指标计算失败: {str(e)}")
            metrics.update(_get_empty_complexity_metrics())
        
        # 3. 峰值形态学指标
        if len(peaks) > 0:
            try:
                morphology_metrics = _calculate_morphology_metrics(peaks, peak_properties, sampling_rate)
                metrics.update(morphology_metrics)
            except Exception as e:
                logger.warning(f"形态学指标计算失败: {str(e)}")
                metrics.update(_get_empty_morphology_metrics())
        else:
            metrics.update(_get_empty_morphology_metrics())
        
        # 4. 时域变异性指标
        try:
            variability_metrics = _calculate_variability_metrics(valid_signal, sampling_rate)
            metrics.update(variability_metrics)
        except Exception as e:
            logger.warning(f"变异性指标计算失败: {str(e)}")
            metrics.update(_get_empty_variability_metrics())
        
        logger.debug(f"高级指标计算完成，共计算 {len(metrics)} 个指标")
        return metrics
        
    except Exception as e:
        logger.error(f"高级指标计算失败: {str(e)}")
        return _get_empty_advanced_metrics()

def calculate_metrics_comprehensive(eda_signal: np.ndarray, peaks: np.ndarray,
                                  peak_properties: Dict[str, Any],
                                  sampling_rate: float = 4.0) -> Dict[str, float]:
    """计算综合EDA指标
    
    结合基础指标和高级指标，提供全面的EDA分析结果。
    
    Args:
        eda_signal: EDA信号数据
        peaks: 峰值位置数组
        peak_properties: 峰值属性字典
        sampling_rate: 采样率（Hz）
        
    Returns:
        综合指标字典
    """
    try:
        logger.debug("开始计算综合EDA指标")
        
        # 计算基础指标
        basic_metrics = calculate_metrics_basic(eda_signal, peaks, peak_properties, sampling_rate)
        
        # 计算高级指标
        advanced_metrics = calculate_metrics_advanced(eda_signal, peaks, peak_properties, sampling_rate)
        
        # 合并所有指标
        comprehensive_metrics = {**basic_metrics, **advanced_metrics}
        
        # 添加综合评估指标
        comprehensive_metrics['total_metrics_count'] = len(comprehensive_metrics)
        
        # 计算综合活跃度评分（基于多个指标的加权平均）
        if 'scr_count' in comprehensive_metrics and 'mean_amplitude' in comprehensive_metrics:
            activity_score = (
                comprehensive_metrics.get('scr_count', 0) * 0.3 +
                comprehensive_metrics.get('mean_amplitude', 0) * 100 * 0.4 +
                comprehensive_metrics.get('scr_rate', 0) * 0.3
            )
            comprehensive_metrics['activity_score'] = float(activity_score)
        
        logger.debug(f"综合指标计算完成，共{len(comprehensive_metrics)}个指标")
        return comprehensive_metrics
        
    except Exception as e:
        logger.error(f"综合指标计算失败: {str(e)}")
        return _get_empty_metrics()

def _calculate_frequency_metrics(signal: np.ndarray, sampling_rate: float) -> Dict[str, float]:
    """计算频域指标"""
    metrics = {}
    
    # FFT分析
    n = len(signal)
    fft_values = fft(signal - np.mean(signal))  # 去除直流分量
    freqs = fftfreq(n, 1/sampling_rate)
    
    # 只取正频率部分
    positive_freqs = freqs[:n//2]
    power_spectrum = np.abs(fft_values[:n//2])**2
    
    # 定义频段
    very_low_freq = (positive_freqs >= 0.0) & (positive_freqs < 0.045)
    low_freq = (positive_freqs >= 0.045) & (positive_freqs < 0.15)
    high_freq = (positive_freqs >= 0.15) & (positive_freqs < 0.4)
    
    # 计算各频段功率
    total_power = np.sum(power_spectrum)
    
    if total_power > 0:
        metrics['power_vlf'] = float(np.sum(power_spectrum[very_low_freq]))
        metrics['power_lf'] = float(np.sum(power_spectrum[low_freq]))
        metrics['power_hf'] = float(np.sum(power_spectrum[high_freq]))
        metrics['power_total'] = float(total_power)
        
        # 相对功率
        metrics['power_vlf_norm'] = metrics['power_vlf'] / total_power
        metrics['power_lf_norm'] = metrics['power_lf'] / total_power
        metrics['power_hf_norm'] = metrics['power_hf'] / total_power
        
        # LF/HF比值
        if metrics['power_hf'] > 0:
            metrics['lf_hf_ratio'] = metrics['power_lf'] / metrics['power_hf']
        else:
            metrics['lf_hf_ratio'] = 0.0
        
        # 主频率
        peak_freq_idx = np.argmax(power_spectrum)
        metrics['peak_frequency'] = float(positive_freqs[peak_freq_idx])
        
        # 频谱重心
        if total_power > 0:
            metrics['spectral_centroid'] = float(np.sum(positive_freqs * power_spectrum) / total_power)
        else:
            metrics['spectral_centroid'] = 0.0
    else:
        metrics.update(_get_empty_frequency_metrics())
    
    return metrics

def _calculate_complexity_metrics(signal: np.ndarray) -> Dict[str, float]:
    """计算信号复杂度指标"""
    metrics = {}
    
    # 1. 样本熵（Sample Entropy）
    try:
        metrics['sample_entropy'] = float(_sample_entropy(signal, m=2, r=0.2*np.std(signal)))
    except:
        metrics['sample_entropy'] = 0.0
    
    # 2. 近似熵（Approximate Entropy）
    try:
        metrics['approximate_entropy'] = float(_approximate_entropy(signal, m=2, r=0.2*np.std(signal)))
    except:
        metrics['approximate_entropy'] = 0.0
    
    # 3. 分形维数
    try:
        metrics['fractal_dimension'] = float(_higuchi_fractal_dimension(signal))
    except:
        metrics['fractal_dimension'] = 1.0
    
    # 4. 去趋势波动分析（DFA）
    try:
        metrics['dfa_alpha'] = float(_detrended_fluctuation_analysis(signal))
    except:
        metrics['dfa_alpha'] = 1.0
    
    return metrics

def _calculate_morphology_metrics(peaks: np.ndarray, peak_properties: Dict[str, Any], 
                                sampling_rate: float) -> Dict[str, float]:
    """计算峰值形态学指标"""
    metrics = {}
    
    if len(peaks) == 0:
        return _get_empty_morphology_metrics()
    
    # 峰值密度
    if len(peaks) > 1:
        peak_intervals = np.diff(peaks) / sampling_rate
        metrics['peak_density'] = float(1.0 / np.mean(peak_intervals))  # 峰值密度（Hz）
        metrics['peak_regularity'] = float(1.0 / (1.0 + np.std(peak_intervals)))  # 峰值规律性
    else:
        metrics['peak_density'] = 0.0
        metrics['peak_regularity'] = 0.0
    
    # 峰值形状指标
    if 'rise_times' in peak_properties and len(peak_properties['rise_times']) > 0:
        rise_times = peak_properties['rise_times']
        metrics['rise_time_mean'] = float(np.mean(rise_times))
        metrics['rise_time_std'] = float(np.std(rise_times))
    else:
        metrics['rise_time_mean'] = 0.0
        metrics['rise_time_std'] = 0.0
    
    if 'fall_times' in peak_properties and len(peak_properties['fall_times']) > 0:
        fall_times = peak_properties['fall_times']
        metrics['fall_time_mean'] = float(np.mean(fall_times))
        metrics['fall_time_std'] = float(np.std(fall_times))
    else:
        metrics['fall_time_mean'] = 0.0
        metrics['fall_time_std'] = 0.0
    
    # 峰值不对称性
    if ('rise_times' in peak_properties and 'fall_times' in peak_properties and 
        len(peak_properties['rise_times']) > 0 and len(peak_properties['fall_times']) > 0):
        rise_times = peak_properties['rise_times']
        fall_times = peak_properties['fall_times']
        asymmetry = (fall_times - rise_times) / (fall_times + rise_times + 1e-8)
        metrics['peak_asymmetry_mean'] = float(np.mean(asymmetry))
        metrics['peak_asymmetry_std'] = float(np.std(asymmetry))
    else:
        metrics['peak_asymmetry_mean'] = 0.0
        metrics['peak_asymmetry_std'] = 0.0
    
    return metrics

def _calculate_variability_metrics(signal: np.ndarray, sampling_rate: float) -> Dict[str, float]:
    """计算时域变异性指标"""
    metrics = {}
    
    # 1. 连续差值的统计量
    diff_signal = np.diff(signal)
    
    metrics['rmssd'] = float(np.sqrt(np.mean(diff_signal**2)))  # 连续差值的均方根
    metrics['sdnn'] = float(np.std(signal))  # 标准差
    metrics['pnn50'] = float(np.sum(np.abs(diff_signal) > 0.05) / len(diff_signal) * 100)  # 大于0.05的差值百分比
    
    # 2. 变异系数
    mean_val = np.mean(signal)
    if mean_val != 0:
        metrics['cv'] = float(np.std(signal) / mean_val)  # 变异系数
    else:
        metrics['cv'] = 0.0
    
    # 3. 四分位距
    q75, q25 = np.percentile(signal, [75, 25])
    metrics['iqr'] = float(q75 - q25)
    
    # 4. 偏度和峰度
    metrics['skewness'] = float(stats.skew(signal))
    metrics['kurtosis'] = float(stats.kurtosis(signal))
    
    return metrics

def _calculate_trend_slope(signal: np.ndarray) -> float:
    """计算信号趋势斜率"""
    if len(signal) < 2:
        return 0.0
    
    x = np.arange(len(signal))
    slope, _, _, _, _ = stats.linregress(x, signal)
    return slope

def _sample_entropy(signal: np.ndarray, m: int = 2, r: float = None) -> float:
    """计算样本熵"""
    if r is None:
        r = 0.2 * np.std(signal)
    
    N = len(signal)
    
    def _maxdist(xi, xj, m):
        return max([abs(ua - va) for ua, va in zip(xi, xj)])
    
    def _phi(m):
        patterns = np.array([signal[i:i+m] for i in range(N - m + 1)])
        C = np.zeros(N - m + 1)
        
        for i in range(N - m + 1):
            template = patterns[i]
            for j in range(N - m + 1):
                if _maxdist(template, patterns[j], m) <= r:
                    C[i] += 1
        
        phi = np.mean(np.log(C / (N - m + 1)))
        return phi
    
    return _phi(m) - _phi(m + 1)

def _approximate_entropy(signal: np.ndarray, m: int = 2, r: float = None) -> float:
    """计算近似熵"""
    if r is None:
        r = 0.2 * np.std(signal)
    
    N = len(signal)
    
    def _maxdist(xi, xj, m):
        return max([abs(ua - va) for ua, va in zip(xi, xj)])
    
    def _phi(m):
        patterns = np.array([signal[i:i+m] for i in range(N - m + 1)])
        C = np.zeros(N - m + 1)
        
        for i in range(N - m + 1):
            template = patterns[i]
            for j in range(N - m + 1):
                if _maxdist(template, patterns[j], m) <= r:
                    C[i] += 1
        
        C = C / (N - m + 1)
        phi = np.mean(np.log(C))
        return phi
    
    return _phi(m) - _phi(m + 1)

def _higuchi_fractal_dimension(signal: np.ndarray, kmax: int = 10) -> float:
    """计算Higuchi分形维数"""
    N = len(signal)
    L = []
    x = []
    
    for k in range(1, kmax + 1):
        Lk = []
        for m in range(k):
            Lmk = 0
            for i in range(1, int((N - m) / k)):
                Lmk += abs(signal[m + i * k] - signal[m + (i - 1) * k])
            Lmk = Lmk * (N - 1) / (((N - m) / k) * k) / k
            Lk.append(Lmk)
        L.append(np.log(np.mean(Lk)))
        x.append(np.log(1.0 / k))
    
    # 线性回归求斜率
    slope, _, _, _, _ = stats.linregress(x, L)
    return slope

def _detrended_fluctuation_analysis(signal: np.ndarray) -> float:
    """去趋势波动分析"""
    N = len(signal)
    
    # 积分信号
    y = np.cumsum(signal - np.mean(signal))
    
    # 定义窗口大小
    scales = np.logspace(0.7, np.log10(N//4), 10).astype(int)
    fluctuations = []
    
    for scale in scales:
        # 分段去趋势
        segments = N // scale
        F = 0
        
        for v in range(segments):
            start = v * scale
            end = (v + 1) * scale
            segment = y[start:end]
            
            # 线性去趋势
            x_seg = np.arange(len(segment))
            coeffs = np.polyfit(x_seg, segment, 1)
            trend = np.polyval(coeffs, x_seg)
            
            F += np.sum((segment - trend) ** 2)
        
        F = np.sqrt(F / (segments * scale))
        fluctuations.append(F)
    
    # 计算DFA指数
    coeffs = np.polyfit(np.log10(scales), np.log10(fluctuations), 1)
    return coeffs[0]

def _get_empty_metrics() -> Dict[str, float]:
    """返回空的基础指标字典"""
    return {
        'mean_eda': 0.0, 'std_eda': 0.0, 'min_eda': 0.0, 'max_eda': 0.0, 'range_eda': 0.0,
        'scr_count': 0.0, 'scr_rate': 0.0, 'scr_amplitude_mean': 0.0, 'scr_amplitude_std': 0.0,
        'scr_amplitude_max': 0.0, 'scr_amplitude_sum': 0.0, 'scr_width_mean': 0.0, 'scr_width_std': 0.0,
        'scr_interval_mean': 0.0, 'scr_interval_std': 0.0, 'scl_mean': 0.0, 'scl_std': 0.0, 'scl_slope': 0.0
    }

def _get_empty_advanced_metrics() -> Dict[str, float]:
    """返回空的高级指标字典"""
    empty = {}
    empty.update(_get_empty_frequency_metrics())
    empty.update(_get_empty_complexity_metrics())
    empty.update(_get_empty_morphology_metrics())
    empty.update(_get_empty_variability_metrics())
    return empty

def _get_empty_frequency_metrics() -> Dict[str, float]:
    """返回空的频域指标字典"""
    return {
        'power_vlf': 0.0, 'power_lf': 0.0, 'power_hf': 0.0, 'power_total': 0.0,
        'power_vlf_norm': 0.0, 'power_lf_norm': 0.0, 'power_hf_norm': 0.0,
        'lf_hf_ratio': 0.0, 'peak_frequency': 0.0, 'spectral_centroid': 0.0
    }

def _get_empty_complexity_metrics() -> Dict[str, float]:
    """返回空的复杂度指标字典"""
    return {
        'sample_entropy': 0.0, 'approximate_entropy': 0.0, 
        'fractal_dimension': 1.0, 'dfa_alpha': 1.0
    }

def _get_empty_morphology_metrics() -> Dict[str, float]:
    """返回空的形态学指标字典"""
    return {
        'peak_density': 0.0, 'peak_regularity': 0.0, 'rise_time_mean': 0.0, 'rise_time_std': 0.0,
        'fall_time_mean': 0.0, 'fall_time_std': 0.0, 'peak_asymmetry_mean': 0.0, 'peak_asymmetry_std': 0.0
    }

def _get_empty_variability_metrics() -> Dict[str, float]:
    """返回空的变异性指标字典"""
    return {
        'rmssd': 0.0, 'sdnn': 0.0, 'pnn50': 0.0, 'cv': 0.0, 
        'iqr': 0.0, 'skewness': 0.0, 'kurtosis': 0.0
    }


def calculate_metrics_neurokit2(eda_signal: np.ndarray, peaks: np.ndarray,
                               peak_properties: Dict[str, Any],
                               sampling_rate: float = 4.0) -> Dict[str, float]:
    """使用NeuroKit2风格计算EDA指标
    
    提供与NeuroKit2库兼容的EDA指标计算方法。
    
    Args:
        eda_signal: EDA信号数据
        peaks: 峰值位置数组
        peak_properties: 峰值属性字典
        sampling_rate: 采样率（Hz）
        
    Returns:
        NeuroKit2风格的指标字典
    """
    try:
        logger.debug("开始计算NeuroKit2风格EDA指标")
        
        # 计算基础指标
        basic_metrics = calculate_metrics_basic(eda_signal, peaks, peak_properties, sampling_rate)
        
        # 转换为NeuroKit2风格的命名
        neurokit2_metrics = {}
        
        # 基本统计量
        neurokit2_metrics['EDA_Mean'] = basic_metrics.get('mean_eda', 0.0)
        neurokit2_metrics['EDA_Std'] = basic_metrics.get('std_eda', 0.0)
        neurokit2_metrics['EDA_Min'] = basic_metrics.get('min_eda', 0.0)
        neurokit2_metrics['EDA_Max'] = basic_metrics.get('max_eda', 0.0)
        
        # SCR相关指标
        neurokit2_metrics['SCR_Peaks_N'] = basic_metrics.get('scr_count', 0.0)
        neurokit2_metrics['SCR_Peaks_Amplitude_Mean'] = basic_metrics.get('scr_amplitude_mean', 0.0)
        neurokit2_metrics['SCR_Peaks_Amplitude_Max'] = basic_metrics.get('scr_amplitude_max', 0.0)
        neurokit2_metrics['SCR_Peaks_Amplitude_Sum'] = basic_metrics.get('scr_amplitude_sum', 0.0)
        neurokit2_metrics['SCR_RiseTime_Mean'] = basic_metrics.get('scr_width_mean', 0.0)
        
        # SCL相关指标
        neurokit2_metrics['SCL_Mean'] = basic_metrics.get('scl_mean', 0.0)
        neurokit2_metrics['SCL_Std'] = basic_metrics.get('scl_std', 0.0)
        
        # 添加一些NeuroKit2特有的指标
        signal_duration = len(eda_signal) / sampling_rate
        neurokit2_metrics['EDA_Duration'] = float(signal_duration)
        
        # 计算SCR频率（每分钟）
        if signal_duration > 0:
            neurokit2_metrics['SCR_Peaks_Rate'] = float(len(peaks) / signal_duration * 60)
        else:
            neurokit2_metrics['SCR_Peaks_Rate'] = 0.0
        
        # 计算恢复时间（简化版本）
        if len(peaks) > 0 and 'widths' in peak_properties:
            widths = peak_properties['widths']
            # 假设恢复时间是峰宽的一半
            recovery_times = np.array(widths) / 2.0
            neurokit2_metrics['SCR_RecoveryTime_Mean'] = float(np.mean(recovery_times))
        else:
            neurokit2_metrics['SCR_RecoveryTime_Mean'] = 0.0
        
        logger.debug(f"NeuroKit2风格指标计算完成，共{len(neurokit2_metrics)}个指标")
        return neurokit2_metrics
        
    except Exception as e:
        logger.error(f"NeuroKit2风格指标计算失败: {str(e)}")
        return {
            'EDA_Mean': 0.0, 'EDA_Std': 0.0, 'EDA_Min': 0.0, 'EDA_Max': 0.0,
            'SCR_Peaks_N': 0.0, 'SCR_Peaks_Amplitude_Mean': 0.0, 'SCR_Peaks_Amplitude_Max': 0.0,
            'SCR_Peaks_Amplitude_Sum': 0.0, 'SCR_RiseTime_Mean': 0.0, 'SCL_Mean': 0.0,
            'SCL_Std': 0.0, 'EDA_Duration': 0.0, 'SCR_Peaks_Rate': 0.0, 'SCR_RecoveryTime_Mean': 0.0
        }

def calculate_metrics_all(eda_signal: np.ndarray, peaks: np.ndarray, 
                         peak_properties: Dict[str, Any], 
                         sampling_rate: float = 4.0) -> Dict[str, float]:
    """计算所有EDA指标
    
    一次性计算基础和高级指标。
    
    Args:
        eda_signal: EDA信号数据
        peaks: 峰值位置数组
        peak_properties: 峰值属性字典
        sampling_rate: 采样率（Hz）
        
    Returns:
        完整的指标字典
    """
    try:
        logger.debug("开始计算所有EDA指标")
        
        # 计算基础指标
        basic_metrics = calculate_metrics_basic(eda_signal, peaks, peak_properties, sampling_rate)
        
        # 计算高级指标
        advanced_metrics = calculate_metrics_advanced(eda_signal, peaks, peak_properties, sampling_rate)
        
        # 合并指标
        all_metrics = {**basic_metrics, **advanced_metrics}
        
        # 添加元信息
        all_metrics['signal_length'] = float(len(eda_signal))
        all_metrics['signal_duration'] = float(len(eda_signal) / sampling_rate)
        all_metrics['sampling_rate'] = float(sampling_rate)
        all_metrics['valid_data_ratio'] = float(np.sum(~np.isnan(eda_signal)) / len(eda_signal))
        
        logger.debug(f"所有指标计算完成，共计算 {len(all_metrics)} 个指标")
        return all_metrics
        
    except Exception as e:
        logger.error(f"所有指标计算失败: {str(e)}")
        return _get_empty_metrics()